package com.cz.nongyetongv5.activity;

import java.util.ArrayList;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.ListViewCheckManagerAdapter;
import com.cz.nongyetongv5.adapter.ListViewCheckManagerAdapter.OnCheckedListener;
import com.cz.nongyetongv5.adapter.ListViewCheckManagerAdapter.ViewHolder;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.ChanPinLeiBie;
import com.cz.nongyetongv5.bean.JianChaDanWei;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.bean.YangPin;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.utils.GoHomeUtil;

public class YangPinXinXiActivity extends Activity implements OnClickListener,
		OnItemClickListener {

	private ViewGroup btnBack = null;

	private View btnSure = null;

	public static final int TO_ADD_YANGPINXINXI = 1;

	/**
	 * 数据
	 */
	private ListView lvJianDuJianChaItemsList = null;

	/**
	 * 列表
	 */
	private ListView lvListView = null;

	/**
	 * 适配器对象
	 */
	private ListViewCheckManagerAdapter adpListView = null;

	/**
	 * 选择所有
	 */
	private Button btnSelectAll = null;

	/**
	 * 清除所有
	 */
	private Button btnDelete = null;

	/**
	 * 用户对象
	 */
	private User user = null;

	private ChanPinLeiBie chanpinleibie1 = null;

	private String planId="0";
	private void initView() {

		btnBack = (ViewGroup) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);








		ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);
		((TextView)this.findViewById(R.id.btnMoreTxt)).setText("添加");
		View view = GoHomeUtil.createPopView(
				getApplicationContext(), new String[] {"添加", "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btn01 = (Button) pop.getContentView().findViewWithTag(
				"btn1");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v == btn01) {
					//	GoHomeUtil.goHome(getApplicationContext());
				}
			}
		};

		btn01.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent to_addyangpin_intent = new Intent(YangPinXinXiActivity.this,
						YangPinAddActivity.class);

				to_addyangpin_intent.putExtra("user", user);
				to_addyangpin_intent.putExtra("planId", planId);
				to_addyangpin_intent.putExtra("data",
						(ArrayList<YangPin>) adpListView.getDatas());
				startActivityForResult(to_addyangpin_intent, TO_ADD_YANGPINXINXI);
				//				if (pop.isShowing()) {
				//					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
				//					pop.dismiss();
				//				} else {
				//					// 显示窗口
				//					pop.showAsDropDown(v);
				//				}

			}
		});











		btnSure =  (View) pop.getContentView().findViewWithTag(
				"btn0");

		btnSure.setOnClickListener(this);

		btnSelectAll = (Button) findViewById(R.id.btnSelectAll);
		btnSelectAll.setOnClickListener(this);

		btnDelete = (Button) findViewById(R.id.btnDelete);
		btnDelete.setOnClickListener(this);

		lvListView = (ListView) findViewById(R.id.lvJianDuJianChaItemsList);
		lvListView.setOnItemClickListener(this);

	}

	private void initConfig() {

		/**
		 * 修改标题
		 */
		TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvTitle.setText(getString(R.string.chanpinjiance_ypxx_title));

		ArrayList<YangPin> datas = (ArrayList<YangPin>) getIntent()
				.getSerializableExtra("yangpins");

		planId=getIntent().getStringExtra("planId");
		if (datas == null) {
			datas = new ArrayList<YangPin>();
		}

		adpListView = new ListViewCheckManagerAdapter(this, datas,
				new OnCheckedListener() {
					@Override
					public void onChecked(int position, int selectCount) {

						if (selectCount == 1) {
							btnSelectAll.setText("编辑");
						} else if (selectCount == adpListView.getCount()) {
							btnSelectAll.setText("全不选");
						} else {
							btnSelectAll.setText("全选");
						}

					}
				});

		lvListView.setAdapter(adpListView);

		user = (User) getIntent().getSerializableExtra("user");

		//		chanpinleibie = (ChanPinLeiBie) getIntent().getSerializableExtra(
		//				"chanpinleibie");

		if (adpListView.getDatas().size() < 1) {
			onClick(btnSure);
		}

	}


	@Override
	protected void onDestroy() {


		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.jiancharenyuan);

		initView();

		initConfig();

	}

	@Override
	public void onClick(View v) {

		/**
		 * 退出
		 */
		if (v == btnBack) {

			Intent data_intent = new Intent();

			data_intent
					.putExtra("yangpins", (ArrayList) adpListView.getDatas());

			setResult(
					ChanPinJianCeNewRecordActivity.TO_YANGPINXINXI_REQUEST_CODE,
					data_intent);

			finish();
		}

		/**
		 * 添加样品
		 */
		if (v == btnSure) {

			Intent to_addyangpin_intent = new Intent(YangPinXinXiActivity.this,
					YangPinAddActivity.class);

			to_addyangpin_intent.putExtra("user", user);
			to_addyangpin_intent.putExtra("planId", planId);
			to_addyangpin_intent.putExtra("data",
					(ArrayList<YangPin>) adpListView.getDatas());

			//to_addyangpin_intent.putExtra("chanpinleibie", chanpinleibie);

			startActivityForResult(to_addyangpin_intent, TO_ADD_YANGPINXINXI);

		}

		/**
		 * 全选
		 */
		if (v == btnSelectAll) {

			if (btnSelectAll.getText().toString().trim().equals("全选")) {

				adpListView.configCheckMap(true);

				adpListView.notifyDataSetChanged();

				btnSelectAll.setText("全不选");
			} else if ("编辑".equals(btnSelectAll.getText().toString().trim())) {

				Integer position = adpListView.getSingleCheckPosition();

				if (position != null) {
					YangPin yangPin = (YangPin) adpListView.getItem(position);

					Intent intent = new Intent(this, YangPinAddActivity.class);

					intent.putExtra("edit", true);

					intent.putExtra("yangpin", yangPin);

					//intent.putExtra("chanpinleibie", chanpinleibie);

					intent.putExtra("user", user);

					startActivityForResult(intent, TO_ADD_YANGPINXINXI);

				}

			} else {

				adpListView.configCheckMap(false);

				adpListView.notifyDataSetChanged();

				btnSelectAll.setText("全选");
			}

		}

		/**
		 * 删除
		 */
		if (v == btnDelete) {

			final CustomDialog deleteDaiShangChuanDialog = new CustomDialog(
					this);

			deleteDaiShangChuanDialog
					.setOnCancleClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							deleteDaiShangChuanDialog.dismiss();
						}
					});

			// 当点击确定的时候
			deleteDaiShangChuanDialog
					.setOnActionClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

							btnSelectAll.setText("全选");

							Map<Integer, Boolean> map = adpListView
									.getCheckMap();

							int count = adpListView.getCount();

							for (int i = 0; i < count; i++) {

								int position = i
										- (count - adpListView.getCount());

								if (map.get(i) != null && map.get(i)) {

									boolean canRemove = true;

									Object data = adpListView.getItem(position);

									if (data instanceof JianChaRenYuan) {

										canRemove = ((JianChaRenYuan) data)
												.isAllowRemove();

									}

									if (data instanceof JianChaDanWei) {
										canRemove = ((JianChaDanWei) data)
												.isAllowRemove();
									}

									if (canRemove) {
										adpListView.getCheckMap().remove(i);

										adpListView.remove(position);
									} else {
										map.put(position, false);
									}

								}
							}

							adpListView.notifyDataSetChanged();

							deleteDaiShangChuanDialog.dismiss();
						}
					});

			deleteDaiShangChuanDialog.setMessage(this.getResources().getString(
					R.string.delete_daishangchuan_message));

			deleteDaiShangChuanDialog
					.setCancleTxt(getString(R.string.jiandujiancha_item_cancle));

			deleteDaiShangChuanDialog
					.setActionTxt(getString(R.string.jiandujiancha_item_sure));

			deleteDaiShangChuanDialog.show();

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 增加完成后..
		if (requestCode == TO_ADD_YANGPINXINXI) {

			if (data != null && data.getSerializableExtra("yangpin") != null) {
				YangPin yangPin = (YangPin) data
						.getSerializableExtra("yangpin");

				boolean edit = data.getExtras().getBoolean("edit", false);

				if (edit) {

					if (adpListView.getDatas().contains(yangPin)) {

						int position = adpListView.getDatas().indexOf(yangPin);

						adpListView.getDatas().remove(position);

						adpListView.getDatas().add(position, yangPin);

						adpListView.notifyDataSetChanged();

						Toast.makeText(YangPinXinXiActivity.this, "编辑成功..",
								Toast.LENGTH_SHORT).show();
					}

				} else {

					if (!adpListView.getDatas().contains(yangPin)) {

						adpListView.getDatas().add(0, yangPin);

						adpListView.notifyDataSetChanged();

					} else {
						Toast.makeText(YangPinXinXiActivity.this, "此样品已经存在..",
								Toast.LENGTH_SHORT).show();
					}
				}

			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View layout, int arg2,
							long arg3) {

		if (layout.getTag() instanceof ViewHolder) {

			ViewHolder holder = (ViewHolder) layout.getTag();

			holder.cbCheck.toggle();
		}

	}

}
